<template>
  <!-- 空车列表 -->
  <div>
    <div style="font-size: 20px;font-weight:700;color:#3a71a8;text-align: center;margin-bottom:10px">空车列表</div>
    <div class="time-wrapper" ref="timeRef">

      <div>
        <el-input size="small" style="width: 110px;margin: 0 5px" placeholder="延长小时" maxlength="5"
          onkeyup="this.value = this.value.replace(/^(0+)|[^\d]+/g, '');" v-model="dg.ps.emptyHour">
        </el-input>

        <el-select size="small" v-model="dg.ps.serviceType" :placeholder="'可跑区域'" style="width: 120px;margin-right: 5px">
          <el-option v-for="(it, i) in serviceTypes" :key="i" :label="it.label" :value="it.val">
          </el-option>
        </el-select>
        <el-date-picker size="small" v-model="dg.ps.setime" type="daterange" range-separator="至"
          start-placeholder="用车开始日期" end-placeholder="用车结束日期" style="width: 200px;margin-right:10px"
          value-format="YYYY-MM-DD" @change="handleCahengTime">
        </el-date-picker>
        <!-- <el-button type="primary" :disabled="idDisabled" style="border-radius: 0;margin-right: -1px"
          icon="el-icon-d-arrow-left" size="mini" @click="handleYear('1')" /> -->
        <!-- <el-button type="primary" style="margin-left: 4px;margin-right: 4px" @click="getToday(0)">今天</el-button> -->
        <!-- <el-button type="primary" :disabled="idDisabled" style="border-radius: 0;margin-left: -1px"
          icon="el-icon-d-arrow-right" size="mini" @click="handleYear('-1')" /> -->

      </div>

    </div>
    <div class="time-wrapper2">
      <el-select multiple collapse-tags clearable v-model="companyNums" :placeholder="'托管单位名称'" size="small"
        style="width: 150px;margin: 0 5px">
        <template #header>
          <el-checkbox v-model="checkAll" :indeterminate="indeterminate" @change="handleCheckAll">
            全选
          </el-checkbox>
        </template>
        <el-option v-for="item in findTrusteeshipMeComboList" :key="item.id" :label="item.companyName"
          :value="item.companyNum">
        </el-option>
      </el-select>
      <el-button size="small" type="primary" @click="getDgList()">搜索</el-button>
    </div>
    <div class="empty-car-list" ref="listRef">
      <div ref="wrapperRef">
        <div ref="carRef" class="car-list">

          <span v-if="dg.list.length === 0" class="c-gray">没有空车数据！</span>
          <template v-else>
            <li class="sort_wrapper">
              <div class="sort_title">序号</div>
              <div class="sort_empty"></div>
              <div class="sort_item" v-for="(n, i) in 22" :key="i">{{ n }}</div>
            </li>
            <!-- <plate-item @change="handleChange" v-for="(item, index) in dg.list" :source="item" :key="index" /> -->
            <plate-item v-for="(item, index) in dg.list" :source="item" :key="index" />
          </template>
        </div>
        <!-- <div v-if="dg.list.length > 0" class="toggleOpen" @click="handleToggle">
          <i :class="getToggleIcon"></i>
        </div> -->
        <!-- <div ref="throwRef" class="throw_wrapper" v-show="isToggle">
          <div class="title">{{ thrower.label }}</div>
          <div class="content_wrapper">
            <div class="items">
              <div class="smallTitle">休假</div>
              <div class="error_item" v-for="(item, index) in thrower.leaveDriverList" :key="index">{{ item.key }}</div>
            </div>
            <div class="items">
              <div class="smallTitle">无主驾</div>
              <div class="error_item" v-for="(item, index) in thrower.noDriverList" :key="index">{{ item.key }}</div>
            </div>
            <div class="items">
              <div class="smallTitle">维修</div>
              <div class="error_item" v-for="(item, index) in thrower.carRepairList" :key="index">{{ item.key }}</div>
            </div>
            <div class="items">
              <div class="smallTitle">机动</div>
              <div class="error_item" v-for="(item, index) in thrower.flexDriverList" :key="index">{{ item.key }}</div>
            </div>
          </div>
        </div> -->
      </div>
    </div>
  </div>
</template>

<script>
import moment from 'moment'
import {
  carScheduleSeatList, findTrusteeshipMeCombo

} from '@/api/login.js'
import plateItem from './plateItem.vue'

export default {
  name: 'EmptyCarList',
  components: { plateItem },
  data() {
    return {
      checkAll: false,
      indeterminate: false,
      companyNums: [],
      findTrusteeshipMeComboList: [],
      idDisabled: false,
      isToday: false,
      isToggle: true, // 默认收起状态
      // 业务类型
      serviceTypes: [
        { val: '', label: '可跑区域（全部）' },
        { val: 'COUNTY_SER', label: '县际业务' },
        { val: 'CITY_SER', label: '市际业务' },
        { val: 'PROVINCE_SER', label: '省际业务' },
      ],
      thrower: {
        label: '异常情况统计',
        noDriverList: [], //  无主驾
        leaveDriverList: [], // 休假
        carRepairList: [], // 维修
        flexDriverList: [],  // 机动
      },
      // 表格数据列表参数
      dg: {
        tbName: 'emptyCarListTb',
        loading: true,
        ps: { // 过滤参数
          // page: 1,
          // rows: 20,
          // 用车起止时间段
          setime: [],
          // 延长小时
          emptyHour: '',
          // 可跑区域
          serviceType: '',
          // 哪一天
          whichDay: '',
        },
        total: 0,
        list: [],

        // 车辆列表编号
        carListNo: 0,
        // 总车辆数
        totalCars: 0,
        // 已用车辆数
        alUseCars: 0,
        // 公司运力
        gsylProp: 0,
        // 总需要车辆数
        totalNeedCars: 0,
        // 已安排车辆数
        alSendCars: 0,
        // 业务运力
        ywylProp: 0,
      },
    }
  },
  computed: {
    getToggleIcon() {
      return this.isToggle ? 'el-icon-caret-left' : 'el-icon-caret-right'
    },
  },
  created() {
    this.sourceData = null
    this.dg.ps.setime = []
    let currentTay = moment().format("YYYY-MM-DD")
    let startTime = currentTay + " 00:00:00"
    let endTime = currentTay + " 23:59:59"
    this.dg.ps.setime = [startTime, endTime]

  },
  watch: {
    companyNums: {
      handler(val, oldVal) {
        if (val.length === 0) {
          this.checkAll = false
          this.indeterminate = false
        } else if (val.length === this.findTrusteeshipMeComboList.length) {
          this.checkAll = true
          this.indeterminate = false
        } else {
          this.indeterminate = true
        }
      },
      immediate: true,  //刷新加载 立马触发一次handler
      deep: true  // 可以深度检测,里面每个值改变都会通知数据更新。
    },
  },
  mounted() {
    let that = this
    // that.$nextTick(() => {
    //   window.addEventListener('resize', that.handleChange, false)
    // })
    findTrusteeshipMeCombo({
      page: {
        pageNum: 1,
        pageSize: 999,
      },
      companyName: '',
    }).then(res => {
  

      that.findTrusteeshipMeComboList = res.data || [];
      setTimeout(() => {
        for (let i = 0; i < that.findTrusteeshipMeComboList.length; i++) {
          that.companyNums.push(that.findTrusteeshipMeComboList[i].companyNum)
        }
        that.checkAll = true
        that.getDgList();
      }, 500);

    })


  },
  // destroyed() {
  //   window.removeEventListener('resize', this.handleChange, false)
  // },
  methods: {
    handleCheckAll(val) {
      this.indeterminate = false
      if (val) {
        this.companyNums = this.findTrusteeshipMeComboList.map((_) => _.companyNum)
      } else {
        this.companyNums = []
      }
    },
    // handleChange() {
    //   let fullRef = this.$refs.timeRef.offsetWidth

    //   let listRef = this.$refs.listRef
    //   let wrapperRef = this.$refs.wrapperRef

    //   let carRef = this.$refs.carRef.offsetWidth
    //   let throwRef = this.$refs.throwRef.offsetWidth

    //   listRef.style.width = fullRef + 'px'
    //   listRef.style.height = '353px'
    //   listRef.style.overflowX = 'scroll'

    //   wrapperRef.style.width = carRef + throwRef + 20 + 'px'
    // },
    handleCahengTime() {
      this.idDisabled = true
    },
    getToday() {
      this.idDisabled = false
      this.isToday = true
      let startTime = moment().format("YYYY-MM-DD") + " 00:00:00"
      let endTime = moment().format("YYYY-MM-DD") + " 23:59:59"
      this.dg.ps.setime = [startTime, endTime]
      this.getDgList();
    },
    handleYear(type) {
      if (!this.isToday) {
        let startTime = moment().format("YYYY-MM-DD") + " 00:00:00"
        let endTime = moment().format("YYYY-MM-DD") + " 23:59:59"
        this.dg.ps.setime = [startTime, endTime]
        this.isToday = true
      }
      let start = this.dg.ps.setime[0].split(' ')[0]
      let end = this.dg.ps.setime[1].split(' ')[0]
      let startTime = moment(start).subtract(type, "days").format("YYYY-MM-DD") + " 00:00:00"
      let endTime = moment(end).subtract(type, "days").format("YYYY-MM-DD") + " 23:59:59"
      this.dg.ps.setime = [startTime, endTime]
      this.getDgList();
    },
    /**
     * 获取-背景颜色
     * @param state 车辆状态 0是正常，大于0就是订单数，repair是维修，leave是请假
     * @param text 说明文本
     */
    isNumber(v) {
      return this.matchReg(/^[0-9]+.?[0-9]*$/, v);
    },
    matchReg(reg, v) {
      if (!(reg.test(v))) {
        return false;
      } else {
        return true;
      }
    },
    getBgColor(state, text) {
      const that = this;

      let kv = {
        // 正常
        zc: '#FFFFFF',
        // 出车
        cc: '#8dea49',
        // 无主驾
        wzj: '#66CCFF',
        // 驾驶员休假
        xj: '#FF00FF',
        // 车辆维修
        wx: '#FFFF00'
      };

      let res = kv['zc']; // 颜色结果 默认正常

      if (!that.isNumber(state)) {
        // 状态码不是数字
        if (state == 'repair') {
          res = kv['wx'];
        } else if (state == 'leave') {
          res = kv['xj'];
        }
      } else {
        // 状态码是数字
        let _state = parseInt(state);

        if (_state > 0 && text == '无主驾') {
          res = kv['wzj'];
        } else if (_state > 0 && text != '无主驾') {
          res = kv['cc'];
        }
      }

      return res;
    },
    /**
     * 获取-驾驶员状态
     * @param code 状态码
     */
    driverStatusText(code) {
      // 0是正常 leave是请假 repair是维修，其余则是日程个数
      let codeText = '';
      code = code + '';
      switch (code) {
        case '0':
          codeText = '正常';
          break;
        case 'leave':
          codeText = '请假';
          break;
        case 'repair':
          codeText = '维修';
          break;
        default:
          codeText = code + '个日程';
      }
      return codeText;
    },

    _paddObj(data) {
      let len = 30 - data.length
      let defaultValue = {
        bgColor: "",
        plateNum: "",
        state: "",
        text: ""
      }
      let ret = Array(len).fill(defaultValue)
      return data.concat(ret)
    },

    /**
     * 获取数据列表
     * @param timeType 时间类型
     */
    getDgList(timeType) {
      const that = this
      let ps = JSON.parse(JSON.stringify(that.dg.ps))

      // 参数处理
      if (ps.setime && ps.setime.length == 2) {
        ps.stime = ps.setime[0];
        ps.etime = ps.setime[1];
      } else {
        ps.stime = "";
        ps.etime = "";
        delete ps.setime;
      }

      if (timeType) {
        ps.whichDay = timeType;

        // 0-今天；1-明天；2-后天；
        let setime = that.U.getSEToday(timeType);

        ps.stime = setime[0].split(' ')[0];
        ps.etime = setime[1].split(' ')[0];
      }
      ps.companyNums = that.companyNums
      carScheduleSeatList(ps).then(res => {

        if (!res || res.code != 1) {
          that.U.qerror('数据请求失败');
        } else {
          // 车辆座位数
          let list = res.data.seatList || [];

          let reslist = [], maxNo = 0;// 结果数组, 最多的车辆数字

          for (let key in list) {
            let it = list[key], sjCars = [], xjCars = [];

            // 省市际车辆
            let sjlist = it.find(a => a.id.indexOf('sj') != -1);
            if (sjlist.other.length > maxNo) maxNo = sjlist.other.length;

            sjlist.other.forEach(a => {

              // 获取-背景颜色
              let colorCode = that.getBgColor(a.id.split('=')[1], a.text);

              sjCars.push({
                plateNum: a.id.split('=')[0],
                state: a.id.split('=')[1],
                text: a.text,
                bgColor: colorCode,
              });

            });


            // 县际车辆
            let xjlist = it.find(a => a.id.indexOf('xj') != -1);
            if (xjlist.other.length > maxNo) maxNo = xjlist.other.length;
            xjlist.other.forEach(a => {
              // 获取-背景颜色
              let colorCode = that.getBgColor(a.id.split('=')[1], a.text);
              xjCars.push({
                plateNum: a.id.split('=')[0],
                state: a.id.split('=')[1],
                text: a.text,
                bgColor: colorCode,
              });
            });

            reslist.push({
              seats: key,
              sjCars: sjCars,
              xjCars: xjCars
            });
          }
          that.dg.carListNo = maxNo;


          that.dg.list = reslist;


          // 右边面板显示数据
          // 无主驾
          let noDriverList = [];
          if (res.noDriver.length > 0) {
            res.noDriver.forEach(it => {
              let stausCode = it.split('=')[1], statusText = that.driverStatusText(stausCode);
              noDriverList.push({
                key: it.split('=')[0],
                status: { val: stausCode, text: statusText }
              });
            });
          }
          this.thrower.noDriverList = this._paddingData(noDriverList)


          // 休假驾驶员
          let leaveDriverList = [];
          if (res.leaveDriver.length > 0) {
            res.leaveDriver.forEach(it => {
              leaveDriverList.push({
                key: '',
                val: ''
              });
            });
          }
          this.thrower.leaveDriverList = this._paddingData(leaveDriverList)


          // 车辆维修
          let carRepairList = [];
          if (res.repairCar.length > 0) {
            res.repairCar.forEach(it => {
              let stausCode = it.split('=')[1], statusText = that.driverStatusText(stausCode);
              carRepairList.push({
                plateNum: it.split('=')[0],
                status: { val: stausCode, text: statusText },
                setime: it.split('=')[2]
              });
            });
          }
          this.thrower.carRepairList = this._paddingData(carRepairList)


          // 机动（顶班驾驶员）
          // let flexDriverList = [];
          // if (res.flexDriver.length > 0) {
          //   res.flexDriver.forEach(it => {
          //     flexDriverList.push({
          //       phone: it.split('-')[1],
          //       name: it.split('-')[0],
          //     });
          //   });
          // }

          // this.thrower.flexDriverList = this._paddingData(flexDriverList)
          let flexDriverList = [];
          if (res.leaveDriver.length > 0) {
            res.leaveDriver.forEach(it => {
              flexDriverList.push({
                phone: it.split('-')[1],
                name: it.split('-')[0],
              });
            });
          }

          this.thrower.flexDriverList = this._paddingData(flexDriverList)



        }
      }).catch(() => {
      });
    },

    handleToggle() {
      this.isToggle = !this.isToggle
    },
    _paddingData(data) {
      let padArr = []
      let len = data.length
      if (len < 15) {
        let num = 15 - len
        for (let i = 0; i < num; i++) {
          padArr.push({
            key: '',
            status: {
              text: '正常',
              value: '0'
            }
          })
        }
      }
      return data.concat(padArr)
    }

  }
}
</script>

<style lang="less" scoped>
.time-wrapper {
  display: flex;
  justify-content: space-between;
  padding-bottom: 5px;

  .bigTitle {
    display: inline-block;
    border-bottom: none;
    padding: 8px 0;
    color: #3A71A8;
    margin-right: 20px;
    font-size: 18px;
    font-weight: bold;
    white-space: nowrap;
  }
}

.time-wrapper2 {
  display: flex;
  padding-bottom: 5px;

  .bigTitle {
    display: inline-block;
    border-bottom: none;
    padding: 8px 0;
    color: #3A71A8;
    margin-right: 20px;
    font-size: 18px;
    font-weight: bold;
    white-space: nowrap;
  }
}

::v-deep(.empty-car-list) {

  @borderColor: #1890ff;

  .car-list {
    width: 40vw;
    display: inline-block;
    vertical-align: top;
    margin-left: 10px;

    .c-gray {
      display: block;
      text-align: center;
      font-size: 15px;
      padding: 20px 0 40px 0;
      color: #929292 !important;
    }

    .sort_wrapper {
      display: inline-block;
      vertical-align: top;
      width: 50px;
      text-align: center;
      border: 1px solid @borderColor;

      .sort_title {
        width: 50px;
        font-size: 12px;
        height: 20px;
        line-height: 20px;
        color: white;
        background: #393B6A;
      }

      .sort_empty {
        width: 50px;
        height: 21px;
        line-height: 20px;
        background: #ecebeb;
        border-bottom: 1px solid @borderColor;
      }

      .sort_item {
        width: 50px;
        height: 20px;
        line-height: 20px;
        font-size: 12px;
        border-bottom: 1px solid @borderColor;

        &:last-child {
          border-bottom: none;
        }
      }
    }
  }

  .toggleOpen {
    width: 20px;
    display: inline-block;
    vertical-align: top;
    text-align: center;
    line-height: 343px;
    height: 343px;
    background: #f5f5f5;
    margin-left: -1px;
    border: 1px solid @borderColor;

    &:hover {
      cursor: pointer;
      background: #e8e8e8;

      i {
        color: @borderColor;
      }
    }
  }

  .throw_wrapper {
    display: inline-block;
    vertical-align: top;
    margin-left: -1px;
    border: 1px solid @borderColor;
    border-top: none;
    box-sizing: border-box;

    .title {
      background: #393B6A;
      color: #fff;
      height: 21px;
      line-height: 20px;
      font-size: 12px;
      text-align: center;
    }

    .content_wrapper {
      display: flex;
      padding-top: 1px;

      .items {
        width: 70px;
        text-align: center;
        font-size: 12px;
        font-weight: normal;
        border-right: 1px solid #1890ff;
        overflow: hidden;

        &:last-child {
          border-right: none;
        }

        .smallTitle {
          height: 20px;
          line-height: 20px;
          background: #ecebeb;
          border-bottom: 1px solid #1890ff;
        }

        .error_item {
          height: 20px;
          line-height: 20px;
          box-sizing: border-box;
          border-bottom: 1px solid #1890ff;

          &:last-child {
            border-bottom: none;
          }
        }
      }
    }
  }

  .toggleMore {
    width: 100%;
    text-align: center;
    padding: 10px 0;
    font-size: 14px;
    border: 1px solid @borderColor;
    border-top: none;

    &:hover {
      cursor: pointer;
      color: @borderColor;
    }
  }

}
</style>
